package guet.imagan.progbuilder;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 表示文本文件
 */
public class TextFile extends File {
	/**
	 * Creates a new <code>File</code> instance by converting the given
	 * pathname string into an abstract pathname.  If the given string is
	 * the empty string, then the result is the empty abstract pathname.
	 *
	 * @param pathname A pathname string
	 * @throws NullPointerException If the <code>pathname</code> argument is <code>null</code>
	 */
	public TextFile(String pathname) {
		super(pathname);
	}

	/**
	 * 从一个普通的File对象创建一个TextFile对象
	 * @param f 文件
	 */
	public TextFile(File f) {
		this(f.getAbsolutePath());
	}

	/**
	 * 返回文本文件的内容
	 *
	 * @return 内容, 若内容为空或文件不存在，都返回null
	 */
	public List<String> getContent() {

		String charset = detectCharset();
		try (
				InputStream ins = new FileInputStream(this);
				InputStreamReader isr = new InputStreamReader(ins, charset);
				BufferedReader br = new BufferedReader(isr);
		) {
			List<String> contents = new ArrayList<>();
			String s = br.readLine();
			while (s != null) {
				if (s.trim().length() > 0) {
					contents.add(s);
				}
				s = br.readLine();
			}
			if (contents.size() > 0)
				return contents;
			return null;
		} catch (FileNotFoundException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
	}

	/**
	 * 探测并返回当前文件的编码
	 *
	 * @return 编码字符串，如“gb2312","utf-8","utf-16","Unicode"
	 */
	public String detectCharset() {
		byte[] head = new byte[3];
		try (
				FileInputStream stream = new FileInputStream(this);
		) {
			stream.read(head);
			String code = "gb2312";  //或GBK
			if (head[0] == -1 && head[1] == -2)
				code = "UTF-16";
			else if (head[0] == -2 && head[1] == -1)
				code = "Unicode";
			else if (head[0] == -17 && head[1] == -69 && head[2] == -65)
				code = "UTF-8";
			return code;
		} catch (IOException e) {
			return "gb2312";
		}
	}
}
